import { _decorator, Component, Sprite} from 'cc';
import { GameAPI } from '../GameAPI';
const { ccclass, property } = _decorator;

@ccclass('AnimComponent')
export class BattleEffectAnimation extends Component {

    @property(Number)
    private interval: number = 0.02;
    @property(Number)
    private maxIndex: number = 3;
    @property(String)
    private imageName: string = "";
    @property(String)
    private frameRootPath: string = "";
    @property(Boolean)
    private isLoop: boolean = true;

    private animSprite: Sprite;
    private curIndex: number = 0;
    private curTime: number = 0;
    public bPlayAnim: boolean = true;

    onLoad() {
        this.animSprite = this.node.getComponent(Sprite);
    }

    public ResetSprite()
    {
        this.animSprite.enabled = false;
    }

    public Init(rootPath, max, name) {
        this.maxIndex = max;
        this.imageName = name;
        this.frameRootPath = rootPath;
        GameAPI.LoadSpriteImage(this.frameRootPath + "/" + this.imageName + this.curIndex + "/spriteFrame", this.animSprite);
        this.animSprite.enabled = true;
    }

    update(deltaTime: number) {
        if (this.bPlayAnim) {
            this.curTime = this.curTime + deltaTime;
            if (this.curTime - this.interval >= 0) {
                this.curIndex = this.curIndex + 1;
                this.UpdateFrame();
                this.curTime = 0;
            }
        }
    }

    UpdateFrame() {
        if (this.curIndex > this.maxIndex) {
            if (this.isLoop == false) {
                this.node.destroy();
                return;
            }
            this.curIndex = 1;
        }
        GameAPI.LoadSpriteImage(this.frameRootPath + "/" + this.imageName + this.curIndex + "/spriteFrame", this.animSprite);
    }

}


